<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      width: 800px;
      margin: 50px;
    }

    #box {
      width: 500px;
      height: 500px;
      border: solid 1px red;
      position: relative;
      margin-top: 10px;
    }

    #move {
      width: 100px;
      height: 100px;
      background-color: blueviolet;
      position: absolute;
    }
  </style>
</head>

<body>
  <div class="container">
    请输入移动距离：<input type="number" id="distance"><br>
    <button id="right-button" type="button">向右走</button>
    <button id="left-button" type="button">向左走</button>

  </div>
  <div id="box">
    <div id="move"></div>
  </div>
</body>
<script>
  var leftButton = document.getElementById('left-button')
  var rightButton = document.getElementById('right-button')
  var move = document.getElementById('move')
  var box = document.getElementById('box')
  var max = box.offsetWidth - move.offsetWidth
  var x = move.offsetLeft

  rightButton.onclick = function (e) {
    animationMove(move, max)

  }
  leftButton.onclick = function (e) {

    animationMove(move, x)
    animationMove(move, max)
  }
  var myId;
  console.log(myId)
  function animationMove(ele, target) {
    var moveDistance = document.getElementById('distance').value
    console.log(moveDistance)
    clearInterval(myId)
    myId = setInterval(function () {
      var x = ele.offsetLeft
      if (x == target) {
        clearInterval(myId)
      } else if (x > target) {
        x -= parseInt(moveDistance)
        console.log('x -= moveDistance=' + x)
        x = x < target ? target : x
        ele.style.left = x + 'px'
      } else if (x < target) {
        x += parseInt(moveDistance)
        console.log('x += moveDistance=' + x)
        x = x > target ? target : x
        ele.style.left = x + 'px'
      }
    }, 30)
  }
</script>

</html>